//
//  CountryTableViewController.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/2.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "CountryTableViewController.h"
#import "TelephonyInfo.h"
#import "CountryCell.h"
@interface CountryTableViewController ()

@end

@implementation CountryTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //取得全部國家的 名字和 代碼
    self.MA_Country = [TelephonyInfo getCountryCodeAll];
    
    //Patrick
    //判斷版本
    version =  [[UIDevice currentDevice].systemVersion floatValue];
    if (version >=8 )
    {
        
        // ios 8以上
        // 初始化 UISearchController。最後一個參數nil表示搜尋結果要顯示在目前的view上
        mySearchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        // 設定那個 Controller 要負責回應searchBar的更新
        mySearchController.searchResultsUpdater = self;
        // NO代表搜尋時背景不要變暗
        mySearchController.dimsBackgroundDuringPresentation = NO;
        
        // 要將searBar的高度設定為44.0，searchBar才會出現，預設值為0.0
        CGRect rect = mySearchController.searchBar.frame;
        rect.size.height = 44.0;
        mySearchController.searchBar.frame = rect;
        
        // 將searchBar放到tableView的上方
        self.tableView.tableHeaderView = mySearchController.searchBar;
        // YES表示 UISearchController 的畫面可以覆蓋目前的 controller
        self.definesPresentationContext = YES;
        
    }
    else if(version <8)
    {
        //ios 7以下
        
        searchBar = [[UISearchBar alloc] init];
        searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
        searchDisplayController.searchResultsDelegate = self;
        searchDisplayController.searchResultsDataSource = self;
        searchDisplayController.delegate = self;
        
        searchBar.frame = CGRectMake(0, 0, 0, 44);
        self.tableView.tableHeaderView = searchBar;
    }
    
    //Patrick
    
    self.title = NSLocalizedString(@"選擇國家", nil);
}

#pragma mark searchBarFor UISearchController
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    //當searchController 作用時
    if (searchController.isActive) {
        //輸入的字串
        NSString *searchString = searchController.searchBar.text;
        //當輸入字串大於零
        if ([searchString length] > 0) {
            //條件是搜尋
            NSPredicate *p = [NSPredicate predicateWithFormat:@"country CONTAINS[cd] %@ OR code CONTAINS[cd] %@", searchString ,searchString];
            //搜尋結果
            searchResult = [self.MA_Country filteredArrayUsingPredicate:p];
        } else {
            searchResult = nil;
        }
    } else {
        searchResult = nil;
    }
    
    
    //
    [self.tableView reloadData];
}

#pragma mark searchDisplayController
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    NSPredicate *p = [NSPredicate predicateWithFormat:@"country CONTAINS[cd] %@ OR code CONTAINS[cd] %@", searchString ,searchString];
    searchResult = [self.MA_Country filteredArrayUsingPredicate:p];
    
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    
    
    //Patrick==========
    if (version >=8 )
    {
        if (searchResult != nil)
        {
            return [searchResult count];

        }
        
        return [self.MA_Country count];
        
    }
    else
    {
        if ([tableView isEqual:self.searchDisplayController.searchResultsTableView])
        {
            return [searchResult count];

        }
        
        return [self.MA_Country count];
    }
    //Patrick==========

    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *cellIdentifier = @"CountryCell";
    CountryCell *countryCell = (CountryCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (version >=8 )
    {
        
        
        // Configure the cell...
        if (countryCell == nil)
        {
            countryCell = [[[NSBundle mainBundle] loadNibNamed:@"CountryCell" owner:self options:nil] objectAtIndex:0];
        }
        
        if (searchResult != nil)
        {
            countryCell.textLabel.text = searchResult[indexPath.row][@"country"];
            countryCell.detailTextLabel.text = [NSString stringWithFormat:@"+ %@",searchResult[indexPath.row][@"code"]];
        
        }
        else
        {
            countryCell.textLabel.text = self.MA_Country[indexPath.row][@"country"];
            countryCell.detailTextLabel.text = [NSString stringWithFormat:@"+ %@",self.MA_Country[indexPath.row][@"code"]];
            
        }
        return countryCell;
    }
    else
    {
        
        
        if (countryCell == nil)
        {
            countryCell = [[[NSBundle mainBundle] loadNibNamed:@"CountryCell" owner:self options:nil] objectAtIndex:0];
        }
        
        if ([tableView isEqual:self.searchDisplayController.searchResultsTableView])
        {
            countryCell.textLabel.text = searchResult[indexPath.row][@"country"];
            countryCell.detailTextLabel.text = [NSString stringWithFormat:@"+ %@",searchResult[indexPath.row][@"code"]];
        }
        else
        {
            countryCell.textLabel.text = self.MA_Country[indexPath.row][@"country"];
            countryCell.detailTextLabel.text = [NSString stringWithFormat:@"+ %@",self.MA_Country[indexPath.row][@"code"]];
        }
        
        return countryCell;
    }
    //}Patrick
    
    /*
    static NSString *cellIdentifier = @"CountryCell";
    
    CountryCell *countryCell = (CountryCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (countryCell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"CountryCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        
        countryCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    //國家
    countryCell.textLabel.text = self.MA_Country[indexPath.row][@"country"];
    //代碼
    countryCell.detailTextLabel.text = self.MA_Country[indexPath.row][@"code"];

    return countryCell;
     */
    

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (searchResult != nil)
    {
        NSLog(@"%@",searchResult[indexPath.row]);
        [_delegate selectCountry:searchResult[indexPath.row]];
    }
    else
    {
        [_delegate selectCountry:self.MA_Country[indexPath.row]];
    }
    
    //選擇完畢 觸發 delegate
    //返回登入畫面
    [self.navigationController popViewControllerAnimated:YES];
}

@end
